package com.app.brilliant.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import weixin.popular.bean.token.Token;
import weixin.popular.client.LocalHttpClient;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class TTUtils {
    public static String jscode2sessionWithJson1(String appid, String appsercret, String code, String anonymousCode){
        long time = System.currentTimeMillis();
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10*1000);
        requestFactory.setReadTimeout(10*1000);
        RestTemplate client = new RestTemplate(requestFactory);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        params.add("appid",appid);
        params.add("secret",appsercret);
        if(code != null&&!"".equals(code.trim())){
            params.add("code", code);
        }
        if(anonymousCode != null&&!"".equals(anonymousCode.trim())){
            params.add("anonymous_code", anonymousCode);
        }
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        ResponseEntity<String> response = null;
        try{
            System.out.println("耗时为1111："+(System.currentTimeMillis()-time)+" " );
            response = client.exchange("https://developer.toutiao.com/api/apps/v2/jscode2session", HttpMethod.POST, requestEntity, String.class);
            System.out.println("耗时为2222："+(System.currentTimeMillis()-time)+" " );
            return response.getBody();
        } catch (HttpClientErrorException e){
            System.out.println( "------------- 出现异常 HttpClientErrorException -------------");
            System.out.println(e.getMessage());
            System.out.println(e.getStatusText());
            System.out.println( "-------------responseBody-------------");
            System.out.println( e.getResponseBodyAsString());
            e.printStackTrace();
            return "";
        }
        catch (Exception e) {
            System.out.println( "------------- HttpRestUtils.httpRestClient() 出现异常 Exception -------------");
            System.out.println(e.getMessage());
            return "";
        }
    }

    public static Token getAccessToken(String appid, String secret){
        HttpUriRequest httpUriRequest = RequestBuilder.get().setUri("https://developer.toutiao.com/api/apps/token").addParameter("appid", appid).addParameter("secret", secret).addParameter("grant_type", "client_credential").build();
        Token accessTokenInfo = LocalHttpClient.executeJsonResult(httpUriRequest, Token.class);
        return accessTokenInfo;
    }

    public static String setUserStorage(String access_token,String openid,String kv_list,String session_key){
        try {
            String signature = HMACSHA256(kv_list,session_key);
            String signMethod = "hmac_sha256";
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri("https://developer.toutiao.com/api/apps/set_user_storage")
                    .addParameter("openid", openid)
                    .addParameter("access_token", access_token)
                    .addParameter("kv_list", kv_list)
                    .addParameter("signature", signature)
                    .addParameter("sig_method", signMethod)
                    .build();
            String responseInfo = LocalHttpClient.executeJsonResult(httpUriRequest, String.class);
            JSONObject jsonObject = JSON.parseObject(responseInfo);
            return jsonObject.getInteger("errcode").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String removeUserStorage(String access_token,String openid,String key,String session_key){
        try {
            String signature = HMACSHA256(key,session_key);
            String signMethod = "hmac_sha256";
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri("https://developer.toutiao.com/api/apps/remove_user_storage")
                    .addParameter("openid", openid)
                    .addParameter("access_token", access_token)
                    .addParameter("key", key)
                    .addParameter("signature", signature)
                    .addParameter("sig_method", signMethod)
                    .build();
            String responseInfo = LocalHttpClient.executeJsonResult(httpUriRequest, String.class);
            JSONObject jsonObject = JSON.parseObject(responseInfo);
            return jsonObject.getInteger("errcode").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toLowerCase();

    }
}
